package main

import (
	"fmt"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"npxy-go/pkg/proxy/client"
	"os"
	"strconv"
	"strings"
)

func main() {
	conf := new(client.Config)

	cmd := &cobra.Command{
		Use:          "npxy-cli",
		Long:         "This is new pxy client",
		SilenceUsage: true,
		RunE: func(cmd *cobra.Command, args []string) error {
			return client.Start(conf)
		},
	}

	flags(conf, cmd.Flags())

	if err := cmd.Execute(); err != nil {
		os.Exit(1)
		return
	}
}


func flags(c *client.Config, fs *pflag.FlagSet) {
	c.Bindings = make([]client.Binding, 0)
	bds := bindings{Bindings: &c.Bindings}

	fs.StringVarP(&c.Bridge, "bridge", "b", "127.0.0.1:8100", "host of bridge") //47.242.185.247
	fs.StringVarP(&c.Secret, "secret", "s", "123456", "secret between server and client")
	fs.Var(&bds, "bindings", "format: 'LOCAL_PORT:PROXY_PORT', witch an be an array. Example: '5500:8080,5507:8081'")
}


type bindings struct {
	Bindings *[]client.Binding
}

func (b bindings) String() string {
	return ""
}

func (b *bindings) Set(str string) error {
	ss := strings.Split(str, ",")
	for _, s := range ss {
		ss := strings.Split(s, ":")
		if len(ss) != 2 {
			return fmt.Errorf("bad args: %s", s)
		}
		lp, elp := strconv.Atoi(ss[0])
		pp, epp := strconv.Atoi(ss[1])

		if elp != nil || epp != nil {
			return fmt.Errorf("bad args: %s", s)
		}

		*b.Bindings = append(*b.Bindings, client.Binding{
			LocalPort:  uint16(lp),
			PortalPort: uint16(pp),
		})
	}

	return nil
}

func (b *bindings) Type() string {
	return "bindings"
}

